import React, { useState, useContext } from 'react';
import cls from 'classnames';
import { FormInstance } from './useForm';
import { FormContext } from './context';
import FieldForm from './FieldForm';
import FormFiled from './FormItem';
import './index.less';

export interface FormProps {
  form: any;
  name?: string;
  children: any;
}

const InternalForm: React.ForwardRefRenderFunction<FormInstance, FormProps> = (props, ref) => {
  const { name = '', form, children } = props;
  const [validateStatus, setValidateStatus] = useState({});
  const value: any = { initForm: form, validateStatus, setValidateStatus };
  form.validateFields = async (fieldName = '') => {
    try {
      await form.validateFormFields(fieldName);
    }catch(e) {
      setValidateStatus(e as any);
    }
  }

  return (
    <div>
      <FormContext.Provider value={value}>
        <FieldForm form={form} id={name} >
          {children}
        </FieldForm>
      </FormContext.Provider>
    </div>
  )
}


const Form = React.forwardRef(InternalForm);


const prefix = 'f_form_item';

const FormItem = (props: any) => {
  const { label, required, name } = props;
  const { validateStatus } = useContext(FormContext);
  console.log(validateStatus, 'validateStatus---')
  return <FormContext.Consumer>

    {
      (consumerProps: any) => {
        const field = consumerProps.initForm.getField(name)
        const innerLabel = label || field.label
        return (
          <div className={prefix}>
            <label className={cls(`${prefix}_label`, {
              [`${prefix}_label_required`]: required,
            })}>
              {innerLabel}
            </label>
            <div className={cls('form_field', {
              [`${prefix}_field_error`]: !!validateStatus[name]
            })}>
              <FormFiled form={consumerProps.initForm} {...props} />
              {
                validateStatus[name] && <div className={`${prefix}_tips_error`}>{validateStatus[name]}</div>
              }
            </div>
          </div>
        )
      }
    }
  </FormContext.Consumer>
}

export {
  Form,
  FormItem
};
